// import api from "./api";
// import apiSetting from "../setting/copywriting";
/*
 *  时间封装方法
 * */
function getTimestamp(time) {
  if (Object.prototype.toString.call(time) === "[object String]") {
    var arr = time.split(/[- :]/),
      _date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]),
      timeStr = Date.parse(_date);
    if (isNaN(timeStr)) {
      timeStr = new Date(time).getTime(); // - /
    }
    return timeStr;
  } else {
    return time;
  }
}
/* 返回转义时间样式 */
function setDownTime(value) {
  let date = getTimestamp(value);
  let nowD = new Date().getTime();
  let today = new Date(
    new Date().getFullYear(),
    new Date().getMonth(),
    new Date().getDate(),
    0,
    0,
    0
  );
  let yesterday = new Date(
    new Date().getFullYear(),
    new Date().getMonth(),
    new Date().getDate() - 1,
    0,
    0,
    0
  );
  if (nowD - 60000 < date) {
    return "刚刚";
  } else if (nowD - 3600000 < date) {
    let m = parseInt(((nowD - date) / 1000 / 60) % 60);
    return `${m}分钟前`;
  } else if (nowD >= date && date >= today) {
    let data = new Date(date);
    let h = data.getHours();
    h = h < 10 ? "0" + h : h;
    let minute = data.getMinutes();
    minute = minute < 10 ? "0" + minute : minute;
    return `${h}-${minute}`;
  } else if (nowD > date && date > yesterday) {
    let data = new Date(date);
    let h = data.getHours();
    h = h < 10 ? "0" + h : h;
    let minute = data.getMinutes();
    minute = minute < 10 ? "0" + minute : minute;
    return `${h}-${minute}`;
  } else {
    // if(date.getFullYear())
    let dateY = new Date(date).getFullYear();
    let nowDY = new Date(nowD).getFullYear();
    if (dateY < nowDY) {
      //去年的
      let data = new Date(date);
      let y = data.getFullYear();
      let m = data.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = data.getDate();
      d = d < 10 ? "0" + d : d;
      return `${y}-${m}-${d}`;
    } else {
      //今年的
      let data = new Date(date);
      let m = data.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = data.getDate();
      d = d < 10 ? "0" + d : d;
      return `${m}-${d}`;
    }
  }
}

/* 页面返回方法 */
function returnPage(len = -1) {
  // this.$router.go(-1);
  window.history.go(len);
  // api.pageClose();
}

/* 图片报错隐藏 */
function hideImg(event) {
  return $(event)
    .parent()
    .hide();
}

/* 返回用户认证信息 */
function returnUserExtentInfo(userInfo) {
  let str = ``;
  // 公司
  if (userInfo.company) {
    str += userInfo.company;
    // 职位
    if (userInfo.office) {
      str += "·" + userInfo.office;
    }
  }
  // 职业
  else if (userInfo.profession) {
    str += userInfo.profession;
    // 行业
    if (userInfo.business) {
      str += "·" + userInfo.business;
    }
  }
  return str;
}

/* 添加绑定事件 */
function addEvent(ev, fn) {
  let userAgent = navigator.userAgent;
  let isAndroid =
    userAgent.indexOf("Android") > -1 || userAgent.indexOf("Adr") > -1; //android终端
  let isIOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  if (isAndroid) {
    document.addEventListener(ev, fn);
  } else if (isIOS) {
    window.addEventListener(ev, fn);
  } else {
    document.addEventListener(ev, fn);
  }
}

/* 移除绑定事件 */
function removeEvent(ev, fn) {
  let userAgent = navigator.userAgent;
  let isAndroid =
    userAgent.indexOf("Android") > -1 || userAgent.indexOf("Adr") > -1; //android终端
  let isIOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  if (isAndroid) {
    document.removeEventListener(ev, fn);
  } else if (isIOS) {
    window.removeEventListener(ev, fn);
  } else {
    document.removeEventListener(ev, fn);
  }
}

/* 发送交互 */
function postMessage(ev) {
  console.log(ev);
  if (window.ReactNativeWebView) {
    window.ReactNativeWebView.postMessage(ev);
  }
}

/* 获取图片的宽高 */
function imgOnload(url, c) {
  let img = new Image();
  img.src = url;
  img.onload = () => {
    return c(img);
  };
  img.onerror = () => {
    return c(img);
  };
}

/* 返回图片路径 */
function topicAvatar(url) {
  if (url && url.indexOf("http") === -1) {
    return apiSetting.image_agency + url;
  } else {
    return url;
  }
}

/* 返回用户头像 */
function userAvatar(url) {
  if (url && url.indexOf("http") === -1) {
    return apiSetting.image_agency + url;
  } else if (url) {
    return url;
  } else if (!url) {
    return require("@/assets/logo.png");
  }
}

/* 封装节流方法 */
function throttle(fn) {
  let canUse = true;
  return function() {
    if (!canUse) {
      return false;
    }
    canUse = false;
    setTimeout(() => {
      fn.apply(this, arguments);
      canUse = true;
    }, 200);
  };
}

function isAdIos() {
  let ua = navigator.userAgent;

  let isAd = ua.indexOf("Android") > -1 || ua.indexOf("Adr") > -1;
  let isIos = !!ua.match(/\(i[^;]+;( u; )? CPU.+Mac OS X/);

  if (isAd) {
    return "ad";
  } else if (isIos) {
    if (
      (window.screen.width === 375 && window.screen.height === 812) ||
      (window.screen.width === 414 && window.screen.height === 896)
    ) {
      return "iosx";
    } else {
      return "ios";
    }
  }
}

/* 压缩图片 */
function reduceImg(file, c) {
  //判断类型是不是图片
  /*if (!/image\/\w+/.test(file.type)) {
    alert("请确保文件为图像类型");
    return false;
  }*/
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function(e) {
    dealImage(this.result, { quality: 1, setWidth: 500 }, function(base) {
      //调用
      var blob = dataURLtoBlob(base);
      var newFile = new File([blob], file.name, { type: file.type });

      return c(newFile);
    });
  };
}

//将base64转为blod
function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

//图片压缩
function dealImage(path, obj, callback) {
  var img = new Image();
  img.src = path;
  img.onload = function() {
    var that = this;
    // 默认按比例压缩
    var w = that.width,
      h = that.height,
      scale = w / h;
    if (w < obj.setWidth) {
      /*!obj.setWidth*/
      w = obj.width || w;
      h = obj.height || w / scale;
    } else {
      h = h * (obj.setWidth / w);
      w = obj.setWidth;
    }
    var quality = obj.quality || 1; // 默认图片质量为0.7
    //生成canvas
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    // 创建属性节点
    var anw = document.createAttribute("width");
    anw.nodeValue = w;
    var anh = document.createAttribute("height");
    anh.nodeValue = h;
    canvas.setAttributeNode(anw);
    canvas.setAttributeNode(anh);
    ctx.drawImage(that, 0, 0, w, h);
    // 图像质量
    if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
      quality = obj.quality;
    }
    // quality值越小，所绘制出的图像越模糊
    var base64 = canvas.toDataURL("image/jpeg", quality);
    // 回调函数返回base64的值
    callback(base64);
  };
}

/* 返回对应高度 */
function returnDomHeight() {
  let domHeight = "";
  let uaType = isAdIos();
  switch (uaType) {
    case "ios":
      domHeight = 26;
      break;
    case "ad":
      domHeight = 28;
      break;
    case "iosx":
      domHeight = 32;
      break;
  }
  return domHeight;
}

/* 键盘失焦事件 */
function blurs() {
  window.scrollTo(0, document.body.scrollTop + 1);
  document.body.scrollTop >= 1 &&
    window.scrollTo(0, document.body.scrollTop - 1);
}

/* 键盘获取焦点 */
function focusins(el) {
  setTimeout(() => {
    el.target.scrollIntoView(true);
  }, 300);
}

/* 判断图片是否符合条件 */
function imgIsVisble(objBox = { width: any, height: any }, type = "large") {
  // 判断图片是否为大图
  if (type === "large") {
    return (
      objBox.width > 338 &&
      objBox.height > 182 &&
      objBox.height / objBox.width < 0.5 &&
      objBox.height !== objBox.width
    );
  } else {
    console.log(
      (objBox.width < 97 && objBox.height < 68) ||
        objBox.height === objBox.width
    );
    return (
      (objBox.width < 97 && objBox.height < 68) ||
      objBox.height === objBox.width
    );
  }
}
/* 取消接口 */
function cacelSend() {
  window.__axiosPromiseArr.forEach((ele, index) => {
    ele.c();
    delete window.__axiosPromiseArr[index];
  });
}

/* 判断路径是否为平台内部 */
function isPathPlatform(path) {
  // apiSetting
  // 测试环境
  if (process.env.VUE_APP_CURRENTMODE === "dev") {
    if (path.indexOf(apiSetting.dev_url) > -1) {
      return true;
    } else {
      return false;
    }
  }
  // 生产环境
  else if (process.env.VUE_APP_CURRENTMODE === "production") {
    if (path.indexOf(apiSetting.pro_url) > -1) {
      return true;
    } else {
      return false;
    }
  }
  // 本地环境
  else if (process.env.NODE_ENV === "development") {
    let OrignUrl = window.location.origin;
    if (path.indexOf(OrignUrl) > -1) {
      return true;
    } else {
      return false;
    }
  }
}

/*
 * 单位转换
 */
function valueFilter(value) {
  if (value >= 10000) {
    return (value / 10000).toFixed(1) + "w";
  } else {
    return value.toFixed(0);
  }
}

export default {
  // 返回时间戳
  setDownTime,

  // 页面返回方法
  returnPage,

  // 隐藏DOm
  hideImg,

  // 返回用户认证信息
  returnUserExtentInfo,

  // 绑定监听事件
  addEvent,

  // 移除绑定事件
  removeEvent,

  // 发送postMessage时间
  postMessage,

  // 获取图片信息
  imgOnload,

  // 返回情报站头像
  topicAvatar,

  // 返回用户头像
  userAvatar,

  // 节流方法
  throttle,

  // 返回系统DOM高度
  returnDomHeight,

  // 键盘失焦事件
  blurs,

  // 键盘获取焦点
  focusins,

  // 压缩图片
  reduceImg,

  // 判断图片范围
  imgIsVisble,

  //获取手机类型
  isAdIos,

  // 取消接口发送
  cacelSend,

  // 判断路径分类
  isPathPlatform,

  // 单位转换
  valueFilter
};
